package com.nandi.emergencyinspection

import android.app.Application
import android.content.Context
import androidx.camera.camera2.Camera2Config
import androidx.camera.core.CameraXConfig
import com.bumptech.glide.Glide
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.model.GlideUrl
import com.luck.picture.lib.app.IApp
import com.luck.picture.lib.engine.PictureSelectorEngine
import com.lzy.okgo.OkGo
import com.lzy.okgo.https.HttpsUtils
import com.nandi.emergencyinspection.customconfig.HttpConfig
import com.nandi.emergencyinspection.customconfig.ShowUIConfig
import com.nandi.emergencyinspection.utils.SSLSocketClient
import com.nandi.emergencyinspection.weight.imgselect.PictureSelectorEngineImp
import com.orhanobut.hawk.Hawk
import com.tbright.ktbaselibrary.global.GlobalConfig
import io.rong.imkit.RongIM
import okhttp3.OkHttpClient
import java.io.InputStream
import java.util.concurrent.TimeUnit
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLSession


class BaseApplication : Application(), IApp, CameraXConfig.Provider {
    override fun onCreate() {
        super.onCreate()
        RongIM.init(this, resources.getString(R.string.appKey))
        Hawk.init(this).build()

        //设置请求方式为okhttp 并设置okhttpClient的证书及超时时间
        val mHttpClient = OkHttpClient().newBuilder()
            .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
            .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
            .build()
        val replace = Glide.get(this)
            .registry.replace(
                GlideUrl::class.java,
                InputStream::class.java,
                OkHttpUrlLoader.Factory(mHttpClient)
            )
        GlobalConfig.init(this, httpConfigProxy = HttpConfig(), showUIProxy = ShowUIConfig())
        initOkGO()
    }

    override fun getAppContext(): Context {
        return this
    }

    override fun getPictureSelectorEngine(): PictureSelectorEngine? {
        return PictureSelectorEngineImp()
    }

    override fun getCameraXConfig(): CameraXConfig {
        return Camera2Config.defaultConfig()
    }

    /**
     * 初始化okGo
     */
    private fun initOkGO() {
        OkGo.getInstance().init(this).okHttpClient = getBuilder()?.build()
    }

    /**
     * @return HttpClient
     */
    private fun getBuilder(): OkHttpClient.Builder? {

        val sslParams = HttpsUtils.getSslSocketFactory()

        val builder = OkHttpClient.Builder()


        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS)
            .readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS)
            .writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS)
            .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
            .hostnameVerifier { hostname, session -> true }
            .build()
        return builder
    }
}